package com.eastidea.live.ot;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import net.sf.json.JSONObject;

import com.eastidea.live.entity.FrmInfMultipleChoice;
import com.eastidea.live.entity.FrmInfMultipleOptions;
import com.eastidea.live.entity.FrmInfSingleLineText;
import com.eastidea.live.entity.FrmUiField;
import com.eastidea.live.entity.FrmUiForm;
import com.eastidea.live.field.multiplechoice.MultipleChoiceOptionsTo;
import com.eastidea.live.field.multiplechoice.MultipleChoiceOt;
import com.eastidea.live.field.multiplechoice.MultipleChoiceTo;
import com.eastidea.live.field.pagebreak.PageBreakOt;
import com.eastidea.live.field.pagebreak.PageBreakTo;
import com.eastidea.live.field.singleline.SingleLineTextOt;
import com.eastidea.live.field.singleline.SingleLineTextTo;
import com.eastidea.live.to.FieldTo;
import com.eastidea.live.to.FormTo;

public class FormOt {
	static public FormTo GenerateFormTo(FrmUiForm po) {
		FormTo to = new FormTo();
		Long id = po.getId(); // > 0? po.getId(): 0;
		to.setId(id);
		to.setHeadline(po.getHeadline());
		to.setOncePerIp(po.getOncePerIp());
		to.setStatus(po.getStatus());
		to.setUpdateTime(po.getUpdateTime());
		to.setQrCode(po.getQrCode());
		return to;
	}
	
	static public FormTo ToFormDetailTo(FrmUiForm form) {
		FormTo formTo = FormOt.GenerateFormTo(form);

		List<FieldTo> fieldTos = new LinkedList<FieldTo>();
		List<FrmUiField> fields = form.getFrmUiFields();

		for (FrmUiField ele : fields) {
			String code = ele.getCode();
			if (code.equals("page_break")) {
				PageBreakTo pageBreakTo = PageBreakOt.GeneratePageBreakTo(ele,
						form);
				fieldTos.add(pageBreakTo);
			} else if (code.equals("single_line_text")) {
				FrmInfSingleLineText singLine = (FrmInfSingleLineText) ele;
				SingleLineTextTo singLineTo = SingleLineTextOt
						.GenerateSingleLineTextTo(singLine, form);

				fieldTos.add(singLineTo);
			} else if (code.equals("multiple_choice")) {
				FrmInfMultipleChoice choice = (FrmInfMultipleChoice) ele;
				MultipleChoiceTo choiceTo = MultipleChoiceOt.GenerateChoiceTo(
						choice, form);

				List<FrmInfMultipleOptions> optionses = choice
						.getFrmInfMultipleChoiceOptionses();
				Collections.sort(optionses);
				for (FrmInfMultipleOptions option : optionses) {
					MultipleChoiceOptionsTo optionTo = MultipleChoiceOt
							.GenerateOptionTo(option, choiceTo, form);
					choiceTo.getOptions().add(optionTo);
				}

				fieldTos.add(choiceTo);
			}
		}
		formTo.setFields(fieldTos);
		return formTo;
	}

}
